/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package licenciamiento;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.*;

public class Timmer extends GenericForwardComposer {

    private Image img;
    private Label msgLb;
    private static final int FILE_SIZE = 100;// 100k
    private static final String SAVE_PATH = /*Executions.getCurrent().getDesktop().getWebApp().getRealPath("/dltaxoa-file/other/ ");*/ "c:\\myfile\\media\\";

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
    }

    //public void onClick$uploadBtn() {
    public void onUpload$uploadBtn(UploadEvent event) {
        msgLb.setValue("");
//        Media media = Fileupload.get();
        Media media = event.getMedia();

        if (media == null) {
            msgLb.setValue("please select a file");
            alert("Seleccione una imagen");
        } else {
            String g = Executions.getCurrent().getContextPath();
            if (media instanceof org.zkoss.image.Image) {
                String type = media.getContentType().split("/")[0];
                if (type.equals("image")) {
                    if (media.getByteData().length > FILE_SIZE * 1024) {
                        msgLb.setValue("File size limit " + FILE_SIZE + "k");
                        alert("Maximo 100 k");
                        return;
                    }
                    org.zkoss.image.Image picture = (org.zkoss.image.Image) media;
                    img.setContent(picture);
                }
                saveFile(media);
            } else {
                alert("El archivo seleccionado no es imagen");
            }
        }


    }

    private void saveFile(Media media) {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            InputStream fin = media.getStreamData();
            in = new BufferedInputStream(fin);

            File baseDir = new File(SAVE_PATH);

            if (!baseDir.exists()) {
                baseDir.mkdirs();
            }

            File file = new File(SAVE_PATH + media.getName());
            if (file.exists()) {
                alert("El nombre del archivo ya exite");
            } else {
                OutputStream fout = new FileOutputStream(file);
                out = new BufferedOutputStream(fout);
                byte buffer[] = new byte[1024];
                int ch = in.read(buffer);
                while (ch != -1) {
                    out.write(buffer, 0, ch);
                    ch = in.read(buffer);
                }
                msgLb.setValue("sucessed upload :" + media.getName());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import javax.faces.application.FacesMessage;
//import javax.faces.context.FacesContext;
//import javax.imageio.stream.FileImageOutputStream;
//import org.zkoss.io.Files;
//import org.zkoss.zk.ui.event.Event;
//import org.zkoss.zk.ui.event.Events;
//import org.zkoss.zk.ui.event.UploadEvent;
//import org.zkoss.zk.ui.util.GenericForwardComposer;
//import org.zkoss.zul.Fileupload;
//import org.zkoss.zul.Image;
//import org.zkoss.zul.Timer;
//import org.zkoss.zul.Window;
//
///**
// *
// * @author SSANCHEZ
// */
//public class Timmer extends GenericForwardComposer {
//
//    Window win;
//    Timer tiempo;
//    private String imageTemp;
//private Image croppeFoto;
//    public void onCreate$win() {
//        //cuando el mouse esta fuera del objecto
//        win.addEventListener(Events.ON_MOUSE_OUT, new org.zkoss.zk.ui.event.EventListener() {
//            public void onEvent(Event t) throws Exception {
//                tiempo.start();
//                System.out.println("empezo");
//
//            }
//        });
//
//        //cuando el mouse esta dentro del objecto
//        win.addEventListener(Events.ON_MOUSE_OVER, new org.zkoss.zk.ui.event.EventListener() {
//            public void onEvent(Event t) throws Exception {
//                tiempo.stop();
//                System.out.println("paro");
//            }
//        });
//
//        tiempo.setDelay(6000);
//        tiempo.setRepeats(true);
//        tiempo.addEventListener(Events.ON_TIMER, new org.zkoss.zk.ui.event.EventListener() {
//            public void onEvent(Event t) throws Exception {
//                alert("hola");
//            }
//        });
//        //tiempo.start();
//
//    }
//    public void actionGuardarFoto(){
//    String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/usuario");
//    String archivo = path + File.separator+ ".jpg";
// 
//    try {
// 
//        if(croppeFoto!=null){
//            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(archivo));
//            imageOutput.write(croppeFoto.getContent().getByteData(), 0, croppeFoto.getContent().getByteData().length);
//            imageOutput.close();
//        }
//        else {
//            OutputStream outStream = new FileOutputStream(new File(archivo));
//            InputStream inputStream = new FileInputStream(path+ "/temp/" + this.imageTemp);
//            byte[] buffer = new byte[6124];
//            int bulk;
//            while (true) {
//                bulk = inputStream.read(buffer);
//                if (bulk < 0) {
//                    break;
//                }
//                outStream.write(buffer, 0, bulk);
//                outStream.flush();
//            }
//            outStream.close();
//            inputStream.close();
//        }
//  
//    } catch (FileNotFoundException e) {
//        e.printStackTrace();
//    } catch (IOException e) {
//        e.printStackTrace();
//    }
//}
// 
//public void uploadFile(UploadEvent event) {
//    try {
//        String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/usuario/temp");
//        String archivo = path + File.separator + event.getName();
// 
//        FileOutputStream fileOutputStream = new FileOutputStream(archivo);
//        byte[] buffer = new byte[6124];
//        int bulk;
//        InputStream inputStream = event.getMedia().getStreamData();
//        while (true) {
//        bulk = inputStream.read(buffer);
//        if (bulk < 0) {
//          break;
//        }
//        fileOutputStream.write(buffer, 0, bulk);
//        fileOutputStream.flush();
//    }
//    fileOutputStream.close();
//    inputStream.close();
// 
// 
//    } catch (IOException e) {
//        e.printStackTrace();
//        FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Error al subir el archivo"));
//    }
//}
//    public void onUpload$bnXML(UploadEvent event) throws IOException {
//        org.zkoss.util.media.Media media = event.getMedia();
//        if (media instanceof org.zkoss.image.Image) {
//            org.zkoss.zul.Image image = new org.zkoss.zul.Image();
//            Fileupload fileupload=new Fileupload();
//
//        } else {
//
//
//        }
//        if (media == null) {
//            alert("Seleccione un archivo...");
//        } else {
//            if (media.getFormat().trim().equals("xml")) {
//                File dest = new File("C:\\bookingdata.xml");
//                Files.copy(dest, media.getStreamData());
//            } else {
//                alert("El archivo seleccionado no es xml");
//            }
//        }
//    }
//}
